package com.example.myapplication;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
/**
 * 屏幕控制服务 - 实现多种屏幕控制方案
 */
public class ScreenControlService {
    private static final String TAG = "ScreenControlService";
    private static final int REQUEST_CODE_ENABLE_ADMIN = 1001;
    
    private Context context;
    private DevicePolicyManager devicePolicyManager;
    private ComponentName deviceAdminComponent;
    private PowerManager powerManager;

    public ScreenControlService(Context context) {
        this.context = context;
        this.devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
        this.deviceAdminComponent = new ComponentName(context, MyDeviceAdminReceiver.class);
        this.powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    }

    /**
     * 检查设备管理员权限是否已激活
     */
    public boolean isDeviceAdminActive() {
        return devicePolicyManager.isAdminActive(deviceAdminComponent);
    }

    /**
     * 请求设备管理员权限
     */
    public void requestDeviceAdminPermission(Activity activity) {
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdminComponent);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "需要设备管理员权限来控制屏幕");
        activity.startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
    }

    /**
     * 方法一：使用DevicePolicyManager锁屏（推荐）
     */
    public ScreenControlResult lockScreenWithDeviceAdmin() {
        try {
            if (!isDeviceAdminActive()) {
                return new ScreenControlResult(false, "设备管理员权限未激活", "NO_DEVICE_ADMIN");
            }

            devicePolicyManager.lockNow();
            Log.d(TAG, "DevicePolicyManager锁屏成功");
            return new ScreenControlResult(true, "DevicePolicyManager锁屏成功", "LOCK_SUCCESS");
            
        } catch (Exception e) {
            Log.e(TAG, "DevicePolicyManager锁屏失败", e);
            return new ScreenControlResult(false, "DevicePolicyManager锁屏失败: " + e.getMessage(), "LOCK_FAILED");
        }
    }

    /**
     * 方法二：使用PowerManager关闭屏幕（需要系统权限）
     */
    public ScreenControlResult turnOffScreenWithPowerManager() {
        try {
            if (powerManager == null) {
                return new ScreenControlResult(false, "PowerManager不可用", "NO_POWER_MANAGER");
            }

            // 检查WAKE_LOCK权限
            if (context.checkCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK) 
                    != PackageManager.PERMISSION_GRANTED) {
                return new ScreenControlResult(false, "缺少WAKE_LOCK权限", "NO_WAKE_LOCK_PERMISSION");
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                // 方法1: 使用反射调用goToSleep方法（需要系统权限）
                try {
                    java.lang.reflect.Method method = powerManager.getClass().getMethod("goToSleep", long.class);
                    method.invoke(powerManager, SystemClock.uptimeMillis());
                    Log.d(TAG, "PowerManager.goToSleep成功");
                    return new ScreenControlResult(true, "PowerManager.goToSleep成功", "SCREEN_OFF_SUCCESS");
                } catch (Exception e) {
                    Log.e(TAG, "PowerManager.goToSleep失败", e);
                }

                // 方法2: 尝试使用PowerManager的其他方法
                try {
                    // 尝试获取唤醒锁然后释放
                    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(
                            PowerManager.PARTIAL_WAKE_LOCK, "ScreenControl::TurnOff");
                    wakeLock.acquire(100); // 短暂获取
                    wakeLock.release(); // 立即释放
                    Log.d(TAG, "PowerManager唤醒锁操作成功");
                    return new ScreenControlResult(true, "PowerManager唤醒锁操作成功", "WAKE_LOCK_SUCCESS");
                } catch (Exception e) {
                    Log.e(TAG, "PowerManager唤醒锁操作失败", e);
                }
            } else {
                return new ScreenControlResult(false, "PowerManager.goToSleep需要API 20+", "API_TOO_LOW");
            }

            return new ScreenControlResult(false, "PowerManager所有方法都失败", "POWER_MANAGER_ALL_FAILED");
            
        } catch (SecurityException e) {
            Log.e(TAG, "PowerManager权限不足", e);
            return new ScreenControlResult(false, "PowerManager权限不足: " + e.getMessage(), "NO_PERMISSION");
        } catch (Exception e) {
            Log.e(TAG, "PowerManager关闭屏幕失败", e);
            return new ScreenControlResult(false, "PowerManager关闭屏幕失败: " + e.getMessage(), "SCREEN_OFF_FAILED");
        }
    }

    /**
     * 方法三：使用KeyguardManager锁屏
     */
    public ScreenControlResult lockScreenWithKeyguard() {
        try {
            KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            if (keyguardManager == null) {
                return new ScreenControlResult(false, "KeyguardManager不可用", "NO_KEYGUARD_MANAGER");
            }

            // 检查权限
            if (context.checkCallingOrSelfPermission(android.Manifest.permission.DISABLE_KEYGUARD) 
                    != PackageManager.PERMISSION_GRANTED) {
                return new ScreenControlResult(false, "缺少DISABLE_KEYGUARD权限", "NO_PERMISSION");
            }

            // 尝试禁用键盘锁并锁屏
            try {
                KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("ScreenControl");
                keyguardLock.disableKeyguard();
                
                // 延迟一点时间让系统处理
                Thread.sleep(100);
                
                Log.d(TAG, "KeyguardManager锁屏成功");
                return new ScreenControlResult(true, "KeyguardManager锁屏成功", "KEYGUARD_SUCCESS");
                
            } catch (Exception e) {
                Log.e(TAG, "KeyguardManager锁屏失败", e);
                return new ScreenControlResult(false, "KeyguardManager锁屏失败: " + e.getMessage(), "KEYGUARD_FAILED");
            }
            
        } catch (Exception e) {
            Log.e(TAG, "KeyguardManager锁屏异常", e);
            return new ScreenControlResult(false, "KeyguardManager锁屏异常: " + e.getMessage(), "KEYGUARD_ERROR");
        }
    }

    /**
     * 方法四：使用Root命令关闭屏幕
     */
    public ScreenControlResult turnOffScreenWithRoot() {
        try {
            // 检查root权限
            if (!hasRootPermission()) {
                return new ScreenControlResult(false, "没有root权限", "NO_ROOT");
            }

            // 尝试多种root命令
            String[] commands = {
                "su -c 'input keyevent KEYCODE_POWER'",
                "su -c 'svc power stayon false'",
                "su -c 'echo 1 > /sys/power/state'"
            };

            for (String command : commands) {
                try {
                    Process process = Runtime.getRuntime().exec(command);
                    process.waitFor();
                    int exitValue = process.exitValue();
                    
                    if (exitValue == 0) {
                        Log.d(TAG, "Root命令执行成功: " + command);
                        return new ScreenControlResult(true, "Root命令执行成功: " + command, "ROOT_SUCCESS");
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Root命令执行失败: " + command, e);
                }
            }

            return new ScreenControlResult(false, "所有Root命令都失败了", "ALL_ROOT_FAILED");
            
        } catch (Exception e) {
            Log.e(TAG, "Root关闭屏幕失败", e);
            return new ScreenControlResult(false, "Root关闭屏幕失败: " + e.getMessage(), "ROOT_ERROR");
        }
    }

    /**
     * 方法五：使用Activity标志关闭屏幕
     */
    public ScreenControlResult turnOffScreenWithActivity() {
        try {
            // 启动一个透明的Activity来关闭屏幕
            Intent intent = new Intent(context, ScreenOffActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            context.startActivity(intent);
            
            Log.d(TAG, "启动ScreenOffActivity成功");
            return new ScreenControlResult(true, "启动ScreenOffActivity成功", "ACTIVITY_SUCCESS");
            
        } catch (Exception e) {
            Log.e(TAG, "启动ScreenOffActivity失败", e);
            return new ScreenControlResult(false, "启动ScreenOffActivity失败: " + e.getMessage(), "ACTIVITY_FAILED");
        }
    }

    /**
     * 综合屏幕关闭方法 - 按优先级尝试多种方案
     */
    public ScreenControlResult turnOffScreen() {
        Log.d(TAG, "开始尝试关闭屏幕...");
        
        // 方法1: DevicePolicyManager锁屏（最推荐）
        ScreenControlResult result = lockScreenWithDeviceAdmin();
        if (result.success) {
            Log.d(TAG, "DevicePolicyManager方案成功");
            return result;
        }
        Log.d(TAG, "DevicePolicyManager方案失败: " + result.message);

        // 方法2: PowerManager关闭屏幕（需要系统权限）
        result = turnOffScreenWithPowerManager();
        if (result.success) {
            Log.d(TAG, "PowerManager方案成功");
            return result;
        }
        Log.d(TAG, "PowerManager方案失败: " + result.message);

        // 方法3: KeyguardManager锁屏
        result = lockScreenWithKeyguard();
        if (result.success) {
            Log.d(TAG, "KeyguardManager方案成功");
            return result;
        }
        Log.d(TAG, "KeyguardManager方案失败: " + result.message);

        // 方法4: Root命令
        result = turnOffScreenWithRoot();
        if (result.success) {
            Log.d(TAG, "Root命令方案成功");
            return result;
        }
        Log.d(TAG, "Root命令方案失败: " + result.message);

        // 方法5: Activity方式
        result = turnOffScreenWithActivity();
        if (result.success) {
            Log.d(TAG, "Activity方案成功");
            return result;
        }
        Log.d(TAG, "Activity方案失败: " + result.message);

        Log.e(TAG, "所有屏幕关闭方法都失败了");
        return new ScreenControlResult(false, "所有屏幕关闭方法都失败了", "ALL_METHODS_FAILED");
    }

    /**
     * 开启屏幕
     */
    public ScreenControlResult turnOnScreen() {
        try {
            // 检查root权限
            if (!hasRootPermission()) {
                return new ScreenControlResult(false, "没有root权限", "NO_ROOT");
            }

            // 尝试多种开启屏幕的命令
            String[] commands = {
                "su -c 'input keyevent KEYCODE_WAKEUP'",
                "su -c 'input tap 500 500'",
                "su -c 'svc power stayon true'"
            };

            for (String command : commands) {
                try {
                    Process process = Runtime.getRuntime().exec(command);
                    process.waitFor();
                    int exitValue = process.exitValue();
                    
                    if (exitValue == 0) {
                        Log.d(TAG, "开启屏幕命令执行成功: " + command);
                        return new ScreenControlResult(true, "开启屏幕命令执行成功: " + command, "SCREEN_ON_SUCCESS");
                    }
                } catch (Exception e) {
                    Log.e(TAG, "开启屏幕命令执行失败: " + command, e);
                }
            }

            return new ScreenControlResult(false, "所有开启屏幕命令都失败了", "ALL_SCREEN_ON_FAILED");
            
        } catch (Exception e) {
            Log.e(TAG, "开启屏幕失败", e);
            return new ScreenControlResult(false, "开启屏幕失败: " + e.getMessage(), "SCREEN_ON_ERROR");
        }
    }

    /**
     * 检测设备是否具有root权限
     */
    private boolean hasRootPermission() {
        try {
            Process process = Runtime.getRuntime().exec("su -c echo 'root_test'");
            process.waitFor();
            int exitValue = process.exitValue();
            return exitValue == 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 屏幕控制结果类
     */
    public static class ScreenControlResult {
        public final boolean success;
        public final String message;
        public final String code;

        public ScreenControlResult(boolean success, String message, String code) {
            this.success = success;
            this.message = message;
            this.code = code;
        }
    }
}
